use axum::{response::Response, extract::Request, middleware::Next};
use axum::http::HeaderValue;
use tracing::debug;

use super::REQUEST_ID_HEADER;

pub async fn get_request_id(mut request: Request, next: Next) -> Response {
    let id = match request.headers().get(REQUEST_ID_HEADER) {
        None => {
            let request_id = uuid::Uuid::now_v7();
            request.headers_mut().insert(
                REQUEST_ID_HEADER,
                request_id.to_string().parse().unwrap()
            );
            request_id.to_string().as_bytes().to_vec()
        }
        Some(v) => {
            v.as_bytes().to_vec()
        }

    };

    let v = id.clone();
    debug!("request id: {}", String::from_utf8(v).unwrap());

    let mut res = next.run(request).await;

    let value = HeaderValue::try_from(id).expect("try request id failed!!!");

    res.headers_mut().insert(
        REQUEST_ID_HEADER,
        value
    );

    res
}